import 'dart:io';
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';

import '../../network/Api.dart';
import '../../network/http_config.dart';
import '../../utils/loading.dart';
import '../../utils/provider.dart';

class Invite3Ui extends StatelessWidget {
  const Invite3Ui({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _Invite3Widget();
  }
}

class _Invite3Widget extends StatefulWidget {
  const _Invite3Widget({Key? key}) : super(key: key);

  @override
  State<_Invite3Widget> createState() => _Invite3WidgetState();
}

class _Invite3WidgetState extends State<_Invite3Widget> {
  String _inviteCode = "";
  String _profileNo = "";

  double _layoutHeight = 730;

  final GlobalKey _rootKey = GlobalKey();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getQr();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final bgHeight = size.width / 756 * 1376;
    return RepaintBoundary(
      key: _rootKey,
      child: Scaffold(
        backgroundColor: const Color(0xFFF8EDFF),
        // appBar: AppBar(
        //   title: Text(
        //     "",
        //     style: TextStyle(
        //         color: ThemeColor.textColor
        //     ),
        //   ),
        //   elevation: 0,
        //   backgroundColor: Colors.white,
        //   iconTheme: const IconThemeData.fallback(),
        // ),
        body: SingleChildScrollView(
          child: GestureDetector(
            onLongPress: () {
              _capturePng();
            },
            child: SizedBox(
              height: _layoutHeight,
              child: Stack(
                alignment: Alignment.topCenter,
                children: [
                  SizedBox(
                    height: size.height,
                  ),
                  Image.asset(
                    "images/ic_invite_bg_1.png",
                    width: size.width,
                    height: bgHeight,
                    fit: BoxFit.cover,
                  ),
                  Positioned(
                    top: bgHeight - 425,
                    child: Container(
                      width: size.width - 50,
                      // height: size.height - bgHeight + 56,
                      decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12)),
                          color: Colors.white),
                      margin: const EdgeInsets.only(bottom: 16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const SizedBox(
                            height: 30,
                          ),
                          Text(
                            '都肆商圈ID：' + _profileNo,
                            style: TextStyle(
                                fontSize: 16, color: Color(0xFF401C66)),
                          ),
                          const SizedBox(
                            height: 10,
                          ),
                          GestureDetector(
                            child: QrImageView(
                              padding: const EdgeInsets.all(0),
                              backgroundColor: Colors.white,
                              data: _getQrInfo(),
                              version: QrVersions.auto,
                              size: 200 / 375 * size.width * 0.8,
                              /*eyeStyle: QrEyeStyle(
                        eyeShape: QrEyeShape.square,
                        color: ThemeColor.mainColor,
                      ),
                      dataModuleStyle: const QrDataModuleStyle(
                        dataModuleShape: QrDataModuleShape.circle,
                        color: Colors.black,
                      )*/
                            ),
                            onTap: () {
                              print("current route: ");
                              // checkPermission(saveAssetsImg());

                              // Navigator.of(context).push(MaterialPageRoute(builder: (ctx) => const DownloadAppUi()));
                            },
                            onLongPress: () {
                              _capturePng();

                              if (!kIsWeb) {
                                print('wwwew');
                              }
                            },
                          ),
                          const SizedBox(
                            height: 10,
                          ),
                          const Text(
                            "情感 相亲 社交 群聊 创业",
                            style: TextStyle(
                                fontSize: 20, color: Color(0xFF401C66)),
                          ),
                          const SizedBox(
                            height: 10,
                          ),
                          Container(
                            width: size.width - 80,
                            padding: const EdgeInsets.symmetric(vertical: 10),
                            decoration: ShapeDecoration(
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(8)),
                                color: const Color(0xFFF7F5FF)),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                _buildIconText(
                                    "images/ic_invite_ax.png", "遇见缘份"),
                                _buildIconText(
                                    "images/ic_invite_hl.png", "新人好礼"),
                                _buildIconText(
                                    "images/ic_invite_jy.png", "免费偶遇"),
                              ],
                            ),
                          ),
                          const SizedBox(
                            height: 16,
                          ),
                        ],
                      ),
                    ),
                  ),
                  Positioned(
                    top: bgHeight - 650,
                    left: 20,
                    child: GestureDetector(
                      child: Container(
                        alignment: Alignment.topLeft,
                        child: const Icon(Icons.arrow_back_ios,
                            size: 25, color: Colors.white),
                      ),
                      onTap: () {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                  Positioned(
                    top: bgHeight - 445,
                    child: Container(
                      alignment: Alignment.center,
                      width: 202 / 375 * size.width * 0.9,
                      height: 36,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          gradient: const LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [Color(0xFF7E3AE5), Color(0xFF4E1DD1)])),
                      child: const Text(
                        '爱要大胆说出口',
                        style: TextStyle(color: Colors.white, fontSize: 16),
                      ),
                    ),
                  ),
                  Positioned(
                    top: bgHeight - 35,
                    child: Container(
                      alignment: Alignment.center,

                      width: 200,
                      height: 30,
                      // 颜色
                      // decoration: BoxDecoration(
                      //   borderRadius: BorderRadius.circular(5),
                      //   color: const Color(0xFF402695),
                      // ),
                      decoration: ShapeDecoration(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(15)),
                        color: const Color(0xFF402695),
                      ),

                      child: const Text(
                        '长按图片下载图片',
                        style: TextStyle(color: Colors.white, fontSize: 12),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildIconText(String icon, String text) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Image.asset(
          icon,
          width: 26,
          height: 26,
        ),
        const SizedBox(
          height: 10,
        ),
        Text(
          text,
          style: const TextStyle(
            color: Color(
              0xFF6C6C6C,
            ),
            fontSize: 10,
          ),
        )
      ],
    );
  }

  String _getQrInfo() {
    print('xxxx   ${HttpConfig.baseUrl}?invite_code=$_inviteCode');
    return _inviteCode.isEmpty
        ? ""
        : HttpConfig.baseUrl + "?invite_code=$_inviteCode";
  }

  _getQr() {
    loading(() async {
      final res = await Api.getInstance().getMemberInfo(Provider.memberId);
      if (res?['data']?['shareCode']?.toString()?.isNotEmpty == true) {
        setState(() {
          _inviteCode = res['data']['shareCode'];
          _profileNo = res['data']['profileNo'];
          print(_inviteCode);
        });
      } else {
        toast("获取邀请码失败！");
      }
      final size = MediaQuery.of(context).size;
      final bgHeight = size.width / 756 * 1376;
      final qrSize = 200 / 375 * size.width;
      setState(() {
        _layoutHeight = bgHeight + qrSize - 80;
      });
    });
  }

  Future<Uint8List?> _capturePng() async {
    try {
      if (!kIsWeb && (Platform.isAndroid || Platform.isIOS)) {
        // PermissionStatus storageStatus = await Permission.storage.status;
        // if (storageStatus != PermissionStatus.granted) {
        //   storageStatus = await Permission.storage.request();
        //   print('ccc $storageStatus');
        //   if (storageStatus != PermissionStatus.granted) {
        //     toast("请先授权");
        //     return null;
        //   }
        // }

        // Permission permission = Permission.storage;
        // PermissionStatus status = await permission.status;
        // // PermissionStatus storageStatus = await Permission.storage.status;
        // if (status.isGranted) {
        //   //权限通过
        // } else if (status.isDenied) {
        //   //权限拒绝， 需要区分IOS和Android，二者不一样
        //   requestPermission(permission);
        // } else if (status.isPermanentlyDenied) {
        //   //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
        //   openAppSettings();
        // } else if (status.isRestricted) {
        //   //活动限制（例如，设置了家长///控件，仅在iOS以上受支持。
        //   openAppSettings();
        // } else {
        //   //第一次申请
        //   requestPermission(permission);
        // }
      }

      RenderRepaintBoundary boundary =
          _rootKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List? pngBytes = byteData?.buffer.asUint8List();
      if (pngBytes != null) {
        final res = await ImageGallerySaver.saveImage(pngBytes);
        if (res == null || res == '') {
          toast("保存失败");
        } else {
          toast("保存到相册成功");
        }
      }
      return pngBytes; //这个对象就是图片数据
    } catch (e) {
      print(e);
    }
    return null;
  }
}

void requestPermission(Permission permission) async {
  //发起权限申请
  PermissionStatus status = await permission.request();
  // 返回权限申请的状态 status
  print('权限状态$status');
  if (status.isPermanentlyDenied) {
    openAppSettings();
  }
}
